package main

import (
	"fmt"
	"log"

	"gitee.com/wangshh_123/cross-pay-go/src/config"
	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	hlpayModels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay/models"

	"gorm.io/gorm"
)

// DatabaseInitializer 数据库初始化器
type DatabaseInitializer struct {
	db *gorm.DB
}

// NewDatabaseInitializer 创建数据库初始化器
func NewDatabaseInitializer() (*DatabaseInitializer, error) {
	// 初始化配置
	if err := config.Init(); err != nil {
		return nil, fmt.Errorf("初始化配置失败: %v", err)
	}

	// 初始化数据库连接
	if err := database.Init(); err != nil {
		return nil, fmt.Errorf("初始化数据库连接失败: %v", err)
	}

	return &DatabaseInitializer{
		db: database.DB,
	}, nil
}

// InitDatabase 初始化数据库
func (di *DatabaseInitializer) InitDatabase() error {
	log.Println("开始初始化数据库...")

	// 自动迁移表结构
	if err := di.autoMigrate(); err != nil {
		return fmt.Errorf("自动迁移失败: %v", err)
	}

	// 初始化基础数据
	if err := di.initBaseData(); err != nil {
		return fmt.Errorf("初始化基础数据失败: %v", err)
	}

	log.Println("数据库初始化完成!")
	return nil
}

// autoMigrate 自动迁移表结构
func (di *DatabaseInitializer) autoMigrate() error {
	log.Println("开始自动迁移表结构...")

	// 定义需要迁移的模型
	modelsToMigrate := []interface{}{
		&models.User{},
		&models.Role{},
		&models.UserRole{},
		&models.UserMatrixAccount{},
		&models.MasterAccount{},
		&models.SubAccount{},
		&models.UserCard{},
		&models.CardStatusHistory{},
		&models.CardFeeConfig{},
		&models.Transaction{},
		&models.Payment{},
		&models.Notification{},
		&models.WebhookNotification{},
		&models.ExchangeLossRule{},
		&models.AdminTransferRecord{},
		&hlpayModels.HlPayCardholder{},
	}

	// 执行迁移
	for _, model := range modelsToMigrate {
		if err := di.db.AutoMigrate(model); err != nil {
			return fmt.Errorf("迁移模型 %T 失败: %v", model, err)
		}
		log.Printf("成功迁移模型: %T", model)
	}

	return nil
}

// initBaseData 初始化基础数据
func (di *DatabaseInitializer) initBaseData() error {
	log.Println("开始初始化基础数据...")

	// 初始化角色数据
	if err := di.initRoles(); err != nil {
		return fmt.Errorf("初始化角色数据失败: %v", err)
	}

	// 初始化管理员用户
	if err := di.initAdminUser(); err != nil {
		return fmt.Errorf("初始化管理员用户失败: %v", err)
	}

	return nil
}

// initRoles 初始化角色数据
func (di *DatabaseInitializer) initRoles() error {
	log.Println("初始化角色数据...")

	roles := []models.Role{
		{
			ID:     1,
			Name:   "超级管理员",
			Status: 1,
			Permissions: models.PermissionsMap{
				"admin:access":       true,
				"user:read":          true,
				"user:write":         true,
				"role:read":          true,
				"role:write":         true,
				"matrix:read":        true,
				"matrix:write":       true,
				"matrix_transfer":    true,
				"card:read":          true,
				"card:write":         true,
				"transaction:read":   true,
				"transaction:write":  true,
				"notification:read":  true,
				"notification:write": true,
				"webhook:read":       true,
				"webhook:write":      true,
				"system:config":      true,
			},
		},
		{
			ID:     2,
			Name:   "普通用户",
			Status: 1,
			Permissions: models.PermissionsMap{
				"user:read":         true,
				"matrix:read":       true,
				"card:read":         true,
				"transaction:read":  true,
				"notification:read": true,
			},
		},
		{
			ID:     3,
			Name:   "代理商",
			Status: 1,
			Permissions: models.PermissionsMap{
				"user:read":         true,
				"matrix:read":       true,
				"matrix:write":      true,
				"card:read":         true,
				"card:write":        true,
				"transaction:read":  true,
				"notification:read": true,
				"webhook:read":      true,
			},
		},
		{
			ID:     4,
			Name:   "财务",
			Status: 1,
			Permissions: models.PermissionsMap{
				"matrix:read":        true,
				"matrix_transfer":    true,
				"transaction:read":   true,
				"transaction:write":  true,
				"notification:read":  true,
				"notification:write": true,
			},
		},
		{
			ID:     5,
			Name:   "子用户",
			Status: 1,
			Permissions: models.PermissionsMap{
				"matrix:read":      true,
				"card:read":        true,
				"transaction:read": true,
			},
		},
	}

	for _, role := range roles {
		var existingRole models.Role
		if err := di.db.Where("id = ?", role.ID).First(&existingRole).Error; err != nil {
			if err == gorm.ErrRecordNotFound {
				if err := di.db.Create(&role).Error; err != nil {
					return fmt.Errorf("创建角色 %s 失败: %v", role.Name, err)
				}
				log.Printf("创建角色: %s", role.Name)
			} else {
				return fmt.Errorf("查询角色失败: %v", err)
			}
		} else {
			log.Printf("角色已存在: %s", role.Name)
		}
	}

	return nil
}

// initAdminUser 初始化管理员用户
func (di *DatabaseInitializer) initAdminUser() error {
	log.Println("初始化管理员用户...")

	// 检查是否已存在管理员用户
	var existingUser models.User
	if err := di.db.Where("username = ?", "admin").First(&existingUser).Error; err == nil {
		log.Println("管理员用户已存在")
		return nil
	}

	// 创建管理员用户
	adminUser := models.User{
		Username: "admin",
		Password: "$2a$10$4ErXSLj/cDQbV1vkAxQu/.mT2uzjvs92d5OCwyWGIc0EdfZuQbH.6", // 默认密码: admin123
		Email:    "admin@crosspay.com",
		Name:     "系统管理员",
		RoleID:   1, // 超级管理员角色
		Status:   1,
	}

	if err := di.db.Create(&adminUser).Error; err != nil {
		return fmt.Errorf("创建管理员用户失败: %v", err)
	}

	// 创建用户角色关联
	userRole := models.UserRole{
		UserID: int64(adminUser.ID),
		RoleID: 1,
	}

	if err := di.db.Create(&userRole).Error; err != nil {
		return fmt.Errorf("创建管理员用户角色关联失败: %v", err)
	}

	log.Println("管理员用户创建成功")
	return nil
}

// ResetDatabase 重置数据库（危险操作）
func (di *DatabaseInitializer) ResetDatabase() error {
	log.Println("警告: 即将重置数据库，这将删除所有数据!")
	log.Println("按 Ctrl+C 取消操作，或按回车键继续...")

	var input string
	fmt.Scanln(&input)

	log.Println("开始重置数据库...")

	// 删除所有表
	if err := di.db.Migrator().DropTable(
		&models.User{},
		&models.Role{},
		&models.UserRole{},
		&models.UserMatrixAccount{},
		&models.MasterAccount{},
		&models.SubAccount{},
		&models.UserCard{},
		&models.CardStatusHistory{},
		&models.CardFeeConfig{},
		&models.Transaction{},
		&models.Payment{},
		&models.Notification{},
		&models.WebhookNotification{},
		&models.ExchangeLossRule{},
		&models.AdminTransferRecord{},
	); err != nil {
		return fmt.Errorf("删除表失败: %v", err)
	}

	log.Println("数据库重置完成，开始重新初始化...")
	return di.InitDatabase()
}

// ShowStatus 显示数据库状态
func (di *DatabaseInitializer) ShowStatus() error {
	log.Println("数据库状态:")

	// 统计各表记录数
	tables := []struct {
		name  string
		model interface{}
	}{
		{"用户", &models.User{}},
		{"角色", &models.Role{}},
		{"用户角色关联", &models.UserRole{}},
		{"矩阵账户", &models.UserMatrixAccount{}},
		{"主账户", &models.MasterAccount{}},
		{"子账户", &models.SubAccount{}},
		{"卡片", &models.UserCard{}},
		{"交易", &models.Transaction{}},
		{"支付", &models.Payment{}},
		{"通知", &models.Notification{}},
		{"Webhook", &models.WebhookNotification{}},
	}

	for _, table := range tables {
		var count int64
		di.db.Model(table.model).Count(&count)
		log.Printf("  %s: %d 条记录", table.name, count)
	}

	return nil
}
